import { app, BrowserWindow, ipcMain, screen } from 'electron'
import { SqlLib } from '../../static/lib/sqlite/SqlLib'
import { SqlLibUser } from '../../static/lib/sqlite/service/SqlLibUser'
import globalConst from '../renderer/content/global/const/index'

let readIni = require('./readini')
let windowses = new Map()
//根据metaId设置是否需要放置录屏，固定的metaID不需要录屏
const noSetProtectionSet = ['countDown','extractNumber', 'charts', 'mindMap', 'Preview', 'tProgress', 'Picture']

const winURL = process.env.NODE_ENV === 'development' ? `http://localhost:9080/resource` : `file://${__dirname}/resource/index.html`

const isAllow = readIni('data', 'screen') || ''
let dbPath = ''
if (process.env.NODE_ENV === 'production') {
  const path = require('path')
  dbPath = path.dirname(process.execPath) + '/resources/data/' + globalConst.global.db
} else {
  dbPath = './data/' + globalConst.global.dbTest
}
const sqlLib = SqlLib.getInstance(dbPath)
// let emptyWin = null

//创建空白窗口
ipcMain.on('creatEmptyResourceWindow', (event) => {
  creatEmptyResourceWindow(true)
})

ipcMain.on('close-all-res', () => {
  windowses.forEach((val, key) => {
    if (key === 'empty') return
    val.destroy()
    windowses.delete(key)
  })
})

let lock = false
let time = 0
//显示空白窗口
ipcMain.on('showResourceHideWindow', (event, message) => {
  if (windowses.get(message.metaId)) {
    windowses.get(message.metaId).show()
    return
  }
  if (!message.metaId) {
    event.sender.send('showResourceWindow-reply', '打开窗口失败！')
    return
  }
  if (windowses.size >= 8) {
    event.sender.send('showResourceWindow-reply', '您同时播放的资源过多，请先关闭其他资源后重试！')
    return
  }
  // if(lock === true){
  //     return
  // }
  // lock = true
  // console.log('showResourceHideWindow')
  let win = windowses.get('empty')
  win && windowses.delete('empty')
  if (!lock && win) {
    lock = true
    if (['countDown','extractNumber', 'tProgress', 'Picture','recognize'].includes(message.metaId) || message.metaType === 'PaperFile') {
      win.unmaximize()
    }
    win.webContents.send('sendMessage', { metaId: message.metaId, userId: message.userId, lessonId: message.lessonId,  res_type: message.res_type,  bookId: message.bookId,onlinePPtId: message.onlinePPtId ,pptType:message.pptType})
    // win.webContents.openDevTools() //打开调试窗口
    // win.loadURL(winURL+ "?metaId=" + message.metaId + "&userId=" + message.userId+"&lessonId="+ message.lessonId);
    // windowses.('empty', null);
    // emptyWin = win
    const user = SqlLibUser.queryCurrentUser(sqlLib)
    const isConfigWhiteUser = user.reverse2 ? user.reverse2 : 'false'
    win.setContentProtection(isConfigWhiteUser !== '1' && isAllow !== 'allow_transcribe' && !noSetProtectionSet.includes(message.metaId))
    win.on('close', () => {
      win = null
      windowses.delete(message.metaId)
      console.log(BrowserWindow.getAllWindows().length)
    })
    creatEmptyResourceWindow(true, message)
    win.show()
    windowses.set(message.metaId, win)
  } else {
    console.log('no empty')
      creatEmptyResourceWindow(false, message)
    // creatEmptyResourceWindow(false, message)
    //create  nomal window
  }
  // lock = false
})

//子页渲染完毕
// ipcMain.on('empty-win-created-successed',()=>{
//     console.log('empty-win-created-successed')
//     lock = false
//     // emptyWin.show()
// })
/**
 *
 * @param  isHide 是否创建隐藏窗口
 * @param  message 创建非可视窗口时穿入该参数
 */
//创建隐藏窗口
const creatEmptyResourceWindow = function (isHide, message) {
  console.log('empty windows has been created')
  if (windowses.size >= 8) {
    return
  }
  
  let cursor = screen.getCursorScreenPoint()
  let curScreen = screen.getDisplayNearestPoint({ x: cursor.x, y: cursor.y })
  let iconDir = ''
  const path = require('path')
  if (process.env.NODE_ENV === 'production') {
    iconDir = path.dirname(process.execPath) + '/resources/data/'
  } else {
    iconDir = './data/'
  }
  let { width, height } = screen.getPrimaryDisplay().workAreaSize
    if (width > 1439 && height > 899 ) {
        width = 1440
        height = 900
    } else {
        width = 1024
        height = 640
    }
   
  let tempWin = new BrowserWindow({
    x: curScreen.bounds.x,
    y: curScreen.bounds.y,
    width: width,
    height: height,
    frame: false, //要创建无边框窗口
    resizable: false, //禁止窗 口大小缩放
    useContentSize: true,
    webPreferences: {
      webSecurity: false,
      nodeIntegration: true,
      devTools: true, //调试工具
    },
    backgroundColor: '#7A7A7A',
    transparent: false, //设置透明
    show: false,
    icon: path.join(iconDir, 'icons', 'bos.ico'),
  })

  tempWin.center()
  tempWin.maximize()
  //禁止拖拽文件到窗口展示
  tempWin.webContents.on('will-navigate', (event) => event.preventDefault())
  // tempWin.webContents.openDevTools() //打开调试窗口
  // tempWin.on('focus',()=>{
  //     tempWin.send('win-get-focus')
  // })
  console.log('message', message, isHide)

  if (message && !isHide) {
    if (['countDown', 'extractNumber','tProgress', 'Picture','recognize'].includes(message.metaId) || message.metaType === 'PaperFile') {
      tempWin.unmaximize()  //
    }
    console.log('show maxwin', message.metaId)
    // console.log(winURL + '?metaId=' + message.metaId + '&userId=' + message.userId + '&lessonId=' + message.lessonId + (message.bookId ? '&lessonId=' + message.bookId : ''))
    tempWin.loadURL(winURL + '?metaId=' + message.metaId + '&userId=' + message.userId + '&lessonId=' + message.lessonId + (message.bookId ? '&lessonId=' + message.bookId : ''))
    windowses.set(message.metaId, tempWin)
    const user = SqlLibUser.queryCurrentUser(sqlLib)
    const isConfigWhiteUser = user.reverse2 ? user.reverse2 : 'false'
    tempWin.setContentProtection(isConfigWhiteUser !== '1' && isAllow !== 'allow_transcribe' && !noSetProtectionSet.includes(message.metaId))
    tempWin.on('close', () => {
      tempWin = null
      windowses.delete(message.metaId)
      console.log(BrowserWindow.getAllWindows().length)
    })
    tempWin.show()
    // tempWin.on('ready-to-show', () => {
    // })
  }

  
  if (isHide) {
    tempWin.loadURL(winURL)
    tempWin.hide()
    tempWin.on('ready-to-show', () => {
      console.log('empty win is ready')
      lock = false
      windowses.set('empty', tempWin)
    })
  }
}

// 忽略 https 证书错误
app.commandLine.appendSwitch('--ignore-certificate-errors', 'true')
app.commandLine.appendSwitch('disable-pinch') // 禁止双指缩放

// 关闭窗口
ipcMain.on('close-resource-window', (event, args) => {
  console.log('ipcMain:close-resource-window')
  if (args.metaId) {
    if (windowses.get(args.metaId)) {
      windowses.get(args.metaId).close()
    }
  }
})
ipcMain.on('close-all-window', (event, args) => {
  windowses.forEach((value, key) => {
    if (value) {
      value.close()
    }
  })
})
// 最小化窗口
ipcMain.on('resource-window-minimize', (event, args) => {
  console.log('ipcMain:resource-window-minimize')
  if (args.metaId) {
    if (windowses.get(args.metaId)) {
      windowses.get(args.metaId).minimize()
    }
  }
})

// 最大化窗口
ipcMain.on('resource-window-normalmize', (event, args) => {
  console.log('ipcMain:resource-window-normalmize')
  if (args.metaId) {
    if (windowses.get(args.metaId)) {
      windowses.get(args.metaId).unmaximize()
      windowses.get(args.metaId).setAlwaysOnTop(false)
    }
  }
})

// 调整窗口大小
ipcMain.on('resource-window-changemize', (event, args) => {
  console.log('ipcMain:resource-window-normalmize')
  if (args.metaId) {
    if (windowses.get(args.metaId)) {
      let cursor = screen.getCursorScreenPoint()
      let curScreen = screen.getDisplayNearestPoint({ x: cursor.x, y: cursor.y })
      windowses.get(args.metaId).setBounds({
        width: 350,
        height: 180,
        x: curScreen.size.width - 350,
        y: curScreen.bounds.y,
        transparent: true,
        fullscreen:true,
        alwaysOnTop:true
      }) 

      windowses.get(args.metaId).setAlwaysOnTop(true)
    }
  }
})

// 最大化窗口
ipcMain.on('resource-window-maximize', (event, args) => {
  console.log('ipcMain:resource-window-maximize')
  if (args.metaId) {
    if (windowses.get(args.metaId)) {
      windowses.get(args.metaId).maximize()
    }
  }
})

// const { ipcRenderer } = require('electron')

ipcMain.on('SET_SOURCE', async (event, sourceId) => {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({
            audio: false,
            video: {
                mandatory: {
                    chromeMediaSource: 'desktop',
                    chromeMediaSourceId: sourceId,
                    minWidth: 1280,
                    maxWidth: 1280,
                    minHeight: 720,
                    maxHeight: 720
                }
            }
        })
        handleStream(stream)
    } catch (e) {
        handleError(e)
    }
})

function handleStream (stream) {
    const video = document.querySelector('video')
    video.srcObject = stream
    video.onloadedmetadata = (e) => video.play()
}

function handleError (e) {
    console.log(e)
}



// module.exports = {
//     creatEmptyResourceWindow:creatEmptyResourceWindow
// }
export default creatEmptyResourceWindow
